package com.intersult.nutils.net.filter;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * @author Dieter Kaeppel
 * @date   10.11.2011
 */
public class ResponseWrapper extends HttpServletResponseWrapper {
	public class WrapperOutputStream extends ServletOutputStream {
	    private OutputStream stream;
	    
	    public WrapperOutputStream(OutputStream stream) {
	        this.stream = stream;
	    }
	    
	    @Override
		public void write(final int b) throws IOException {
	        stream.write(b);
	    }
	    @Override
		public void write(final byte[] b) throws IOException {
	        stream.write(b);
	    }
	    @Override
		public void write(final byte[] b, final int off, final int len) throws IOException {
	        stream.write(b, off, len);
	    }
	}

	private WrapperOutputStream outputStream;
	private PrintWriter writer;
	private int status;
	
	public ResponseWrapper(HttpServletResponse response, OutputStream outputStream) {
		super(response);
		this.outputStream = new WrapperOutputStream(outputStream);
	}
	
	@Override
	public ServletOutputStream getOutputStream() {
		return outputStream;
	}
	
    @Override
	public PrintWriter getWriter() throws IOException {
        if (writer == null)
            writer = new PrintWriter(new OutputStreamWriter(outputStream, getCharacterEncoding()), true);
        return writer;
    }
    
    @Override
    public void flushBuffer() throws IOException {
    	if (writer != null)
    		writer.flush();
    	outputStream.flush();
    }
    
    public int getStatus() {
		return status;
	}
    @Override
    public void setStatus(int status) {
    	this.status = status;
		super.setStatus(status);
    }
    @Override
    public void setStatus(int status, String statusMessage) {
    	this.status = status;
		super.setStatus(status, statusMessage);
    }
}